﻿using System.Collections.Generic;

namespace StudyDemo.Console
{
    public class Common
    {
        private static List<System.IO.FileInfo> listInfo = new List<System.IO.FileInfo>();

        /// <summary>
        /// 获取指定目录下所有文件的文件信息
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static List<System.IO.FileInfo> GetFileInfos(string path)
        {
            listInfo = new List<System.IO.FileInfo>();
            GetDirs(path);
            return listInfo;
        }

        /// <summary>
        /// 获取指定目录下所有文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static void GetDirs(string path)
        {
            var dirs = System.IO.Directory.GetDirectories(path);
            foreach (var item in dirs)
            {
                if (!item.EndsWith("$RECYCLE.BIN") && !item.EndsWith("System Volume Information"))
                {
                    GetFiles(item);
                    GetDirs(item);
                }
            }
        }
        /// <summary>
        /// 获取指定目录下所有文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static void GetFiles(string path)
        {
            var files = System.IO.Directory.GetFiles(path);
            if (files.Length == 0)
                return;
            foreach (var item in files)
            {
                if (item.Contains("'"))
                {
                    //list.Add(item);
                    continue;
                }
                listInfo.Add(new System.IO.FileInfo(item));
            }
        }

        /// <summary>
        /// 文件信息写入数据库
        /// </summary>
        /// <param name="listInfo">文件信息</param>
        public static void WrittenDB(List<System.IO.FileInfo> listInfo)
        {
            using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection("server=.;database=AppsDB;uid=sa;pwd=123456"))
            {
                conn.Open();
                //清空数据表
                System.Data.SqlClient.SqlCommand cmd0 = new System.Data.SqlClient.SqlCommand("truncate table AAAAA", conn);
                _ = cmd0.ExecuteNonQuery();
                foreach (var fileInfo in listInfo)
                {
                    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(
                        $"INSERT INTO AAAAA ([Extension], [Length], [LastWriteTime], [FullName]) VALUES (N'" +
                        $"{fileInfo.Extension}',{fileInfo.Length}, N'{fileInfo.LastWriteTime}', N'{fileInfo.FullName}');", conn);
                    _ = cmd.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// PPT文件转PDF
        /// </summary>
        /// <param name="source">源文件全路径</param>
        /// <param name="newFilePath">目标文件路径</param>
        /// <returns></returns>
        public static bool PptToPdf(string source, string newFilePath,bool IsDelete =false)
        {
            var type = System.Type.GetTypeFromProgID("KWPP.Application");
            dynamic wps = System.Activator.CreateInstance(type);
            try
            {
                //转pdf（如果批量多个文件，可以再这里循环文件抓换，避免频繁打开WPS）
                var doc = wps.Presentations.Open(source, PowerPoint.MsoTriState.msoCTrue, PowerPoint.MsoTriState.msoCTrue,
                    PowerPoint.MsoTriState.msoCTrue);
                doc.SaveAs(newFilePath, PowerPoint.PpSaveAsFileType.ppSaveAsPDF, PowerPoint.MsoTriState.msoTrue);
                doc.Close();
                //删除源文件
                if (IsDelete)
                    System.IO.File.Delete(source);
            }
            catch (System.Exception)
            {
                //添加你的日志代码
                return false;
            }
            finally
            {
                wps.Quit();
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
            }
            return true;
        }

        /// <summary>
        /// PPT文件转PPTX
        /// </summary>
        /// <param name="source">源文件全路径</param>
        /// <param name="newFilePath">目标文件路径</param>
        /// <returns></returns>
        public static bool PptToPptx(string source, string newFilePath, bool IsDelete = false)
        {
            var type = System.Type.GetTypeFromProgID("KWPP.Application");
            dynamic wps = System.Activator.CreateInstance(type);
            try
            {
                //转PPTX（如果批量多个文件，可以再这里循环文件抓换，避免频繁打开WPS）
                dynamic doc = wps.Presentations.Open(source,
                                                     PowerPoint.MsoTriState.msoCTrue,
                                                     PowerPoint.MsoTriState.msoCTrue,
                                                     PowerPoint.MsoTriState.msoCTrue);
                doc.SaveAs(newFilePath,
                           PowerPoint.PpSaveAsFileType.ppSaveAsPresentation,
                           PowerPoint.MsoTriState.msoTrue);
                doc.Close();
                //删除源文件
                if (IsDelete)
                    System.IO.File.Delete(source);
            }
            catch (System.Exception e)
            {
                //添加你的日志代码
                return false;
            }
            finally
            {
                wps.Quit();
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
            }
            return true;
        }


        /// <summary>
        /// DOC文件转DOCX
        /// </summary>
        /// <param name="source">源文件全路径</param>
        /// <param name="newFilePath">目标文件路径</param>
        /// <returns></returns>
        public static bool DocToDocx(string source, string newFilePath, bool IsDelete = false)
        {
            var type = System.Type.GetTypeFromProgID("KWps.Application");
            dynamic wps = System.Activator.CreateInstance(type);
            try
            {
                //转DOCX（如果批量多个文件，可以再这里循环文件抓换，避免频繁打开WPS）
                var doc = wps.Documents.Open(source, Visible: false);
                doc.SaveAs2(newFilePath, 12);
                doc.Close();
                //删除源文件
                if (IsDelete)
                    System.IO.File.Delete(source);
            }
            catch (System.Exception e)
            {
                //添加你的日志代码
                return false;
            }
            finally
            {
                wps.Quit();
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
            }
            return true;
        }

    }
}
